<template>
  <div class="json-editor">
    <textarea ref="textarea" />
  </div>
</template>

<script>
export default {
  name: 'JsonEditor'
}
</script>

<script setup>
import { defineProps, ref, watch, defineEmits, onMounted, defineExpose } from 'vue'
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/rubyblue.css'
// import 'script-loader!jsonlint'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'

const props = defineProps({
  modelValue: {
    type: String,
    deafult: ''
  }
})

const textarea = ref()
let jsonEditor = ref(false)

watch(() => props.modelValue, value => {
  const editorValue = jsonEditor.getValue()
  if (value !== editorValue) {
    jsonEditor.setValue(JSON.stringify(this.value, null, 2))
  }
})

const emits = defineEmits(['update:modelValue', 'changed'])

onMounted(() => {
  jsonEditor = CodeMirror.fromTextArea(textarea.value, {
    lineNumbers: true,
    mode: 'application/json',
    gutters: ['CodeMirror-lint-markers'],
    theme: 'rubyblue',
    lint: true
  })
  jsonEditor.setValue(JSON.stringify(props.modelValue, null, 2))
  jsonEditor.on('change', cm => {
    emits('changed', cm.getValue())
    emits('update:modelValue', cm.getValue)
  })
})

const getValue = () => jsonEditor.getValue()

defineExpose({
  getValue
})

</script>

<style lang="scss" scoped>
.json-editor {
  height: 100%;
  position: relative;

  :deep(.CodeMirror) {
    height: auto;
    min-height: 300px;
  }

  :deep(.CodeMirror-scroll) {
    min-height: 300px;
  }

  :deep(.cm-s-rubyblue span.cm-string) {
    color: #F08047;
  }
}
</style>
